package com.weedsdream.app.colorplate

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.weedsdream.app.colorplate.Axis3.Type.B
import com.weedsdream.app.colorplate.Axis3.Type.G
import com.weedsdream.app.colorplate.Axis3.Type.R
import com.weedsdream.app.colorplate.ColorSetType.使用时间
import com.weedsdream.app.colorplate.ColorSetType.使用量
import com.weedsdream.app.colorplate.ColorSetType.收藏
import com.weedsdream.app.struct.drafts
import com.weedsdream.compose.HLine
import com.weedsdream.compose.Space
import com.weedsdream.compose.TextField
import com.weedsdream.compose.VLine
import com.weedsdream.function.longTime2String
import okhttp3.internal.toHexString

/**颜色集使用的结构
 * @property id 颜色argb转Int
 * @property color 颜色
 * @property time 最后使用时间
 * @property useCount 此颜色的笔迹数量
 * @property reColor color的反色*/
data class ColorSetData(val color: Color) {
    val id: Int
    var time = 0L
    var useCount = 0
    val reColor: Color

    init {
        val r = (color.red * 255).toInt()
        val g = (color.green * 255).toInt()
        val b = (color.blue * 255).toInt()
        id = (0xff shl 24) or (r shl 16) or (g shl 8) or b
        reColor = Color(255 - r, 255 - g, 255 - b)
    }

    /**从id反建Color*/
    companion object {
        fun int2color(int: Int): Color {
            val r = (int shr 16) and 0xff
            val g = (int shr 8) and 0xff
            val b = int and 0xff
            return Color(r, g, b)
        }
    }

    override fun hashCode() = id
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is ColorSetData) return false
        return id == other.id
    }
}

/**颜色集*/
val colorSet = mapOf(
    Pair(使用量, mutableStateListOf<ColorSetData>()), Pair(使用时间, mutableStateListOf()),
    Pair(收藏, mutableStateListOf())
)

/**颜色集类型*/
@Suppress("EnumEntryName", "NonAsciiCharacters")
enum class ColorSetType {
    使用量, 使用时间, 收藏
}

/**取色板*/
@Preview(widthDp = 600, heightDp = 350)
@Composable
fun ColorPlateMain() {
    colorSet[使用时间]?.sortByDescending { it.time }
    colorSet[使用量]?.apply {
        clear()
        for ((color, list) in drafts) {
            val csd = ColorSetData(color)
            csd.useCount = list.size
            add(csd)
        }
        sortByDescending { it.useCount }
    }
    Column(Modifier.fillMaxSize()) {
        Row(Modifier.weight(2f)) {
            Box(
                Modifier
                    .weight(2f)
                    .fillMaxSize()
            ) {
                //取色盘
                Box(
                    Modifier
                        .padding(start = 50.dp)
                        .fillMaxSize()
                        .align(Alignment.BottomCenter)
                ) { ColorPlate() }
                //当前选中色示例
                val curC = ColorSetData(curRGB)
                Box(
                    Modifier
                        .size(80.dp)
                        .clickable {
                            if (!colorSet[收藏]!!.contains(curC)) {//不存在时收藏并排序
                                colorSet[收藏]!!.add(curC)
                                colorSet[收藏]!!.sortByDescending { it.id }
                            } else {
                                colorSet[收藏]!!.remove(curC)
                            }
                        }) {
                    Space(curRGB, 1f)
                    Text(
                        if (colorSet[收藏]!!.contains(curC)) "取消收藏" else "收藏",
                        Modifier.align(Alignment.Center)
                    )
                }
                //当前选中色数值
                Box(
                    Modifier
                        .padding(5.dp)
                        .align(Alignment.BottomStart)
                ) { CurRGBShow() }
            }
            VLine()
            //右侧色板列表
            Column(Modifier.weight(1f)) { ColorBlock() }
        }
        HLine()
        PenValue()
    }
}

/**当前选中色数值*/
@Composable
private fun CurRGBShow() {
    Column {
        if (Axis3.type != null) Row(
            Modifier
                .height(20.dp)
                .padding(vertical = 3.dp)
        ) {
            val tp = Axis3.type!!
            Icon(
                Icons.Default.Star, null, Modifier
                    .size(15.dp)
                    .align(Alignment.CenterVertically),
                when (Axis3.type!!) {
                    R -> Color(Axis3.rgb, 0, 0)
                    G -> Color(0, Axis3.rgb, 0)
                    B -> Color(0, 0, Axis3.rgb)
                }
            )
            Text(
                when (tp) {
                    R -> "(红) = "
                    G -> "(绿) = "
                    B -> "(蓝) = "
                } + "${Axis3.rgb}", fontSize = 12.sp
            )
        }
        listOf(
            Pair(R, (curRGB.red * 255).toInt()), Pair(G, (curRGB.green * 255).toInt()),
            Pair(B, (curRGB.blue * 255).toInt())
        ).forEach {//红绿蓝数值
            Row(Modifier.padding(vertical = 3.dp)) {
                Text(
                    text = when (it.first) {
                        R -> "红 = "
                        G -> "绿 = "
                        B -> "蓝 = "
                    }, fontSize = 12.sp
                )
                val strState = remember { mutableStateOf("") }//只在首次重组执行
                strState.value = it.second.toString()//保证每次重组都能更新显示值
                TextField(strState, background = Color.Unspecified, fontSize = 12.sp, width = 40.dp,
                    height = 20.dp, outPadding = PaddingValues(0.dp),
                    inPadding = PaddingValues(0.dp), onValueChange = { s ->
                        val value = (s.toIntOrNull() ?: 0).let {//数值有效性验证
                            if (it < 0) 0 else if (it > 255) 255 else it
                        }
                        val r = if (it.first == R) value else (curRGB.red * 255).toInt()
                        val g = if (it.first == G) value else (curRGB.green * 255).toInt()
                        val b = if (it.first == B) value else (curRGB.blue * 255).toInt()
                        curRGB = Color(r, g, b)
                        curPos = color2offset(curRGB).let {
                            IntOffset(it.x.toInt(), it.y.toInt())
                        }
                        //重算第三轴
                        Axis3.computeAxis3(r, g, b)
                    })
                if (Axis3.type == it.first && Axis3.rgb == it.second) Icon(//第三轴影响标注
                    Icons.Default.Star, null, Modifier
                        .size(15.dp)
                        .align(Alignment.CenterVertically), when (it.first) {
                        R -> Color(Axis3.rgb, 0, 0)
                        G -> Color(0, Axis3.rgb, 0)
                        B -> Color(0, 0, Axis3.rgb)
                    }
                )
            }
        }
    }
}

/**右侧色块列表*/
@Composable
private fun ColorBlock() {
    var curTp by remember { mutableStateOf(colorSet.keys.elementAt(0)) }
    //类型标题
    Row(Modifier.height(30.dp)) {
        colorSet.keys.forEach { tp ->
            Box(
                Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .clickable { curTp = tp }) {
                Text(
                    tp.name, color = if (tp == curTp) Color.Cyan else Color.Black,
                    modifier = Modifier.align(Alignment.Center)
                )
            }
            VLine()
        }
    }
    HLine()
    //色块列表
    LazyColumn(Modifier.fillMaxSize()) {
        colorSet[curTp]!!.chunked(4).forEach { lst ->
            item {
                Row(
                    Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                ) {
                    lst.forEach {
                        Box(
                            Modifier
                                .weight(1f)
                                .fillMaxHeight()
                                .padding(3.dp)
                                .background(it.color)
                                .clickable {
                                    curRGB = it.color
                                    val r = (curRGB.red * 255).toInt()
                                    val g = (curRGB.green * 255).toInt()
                                    val b = (curRGB.blue * 255).toInt()
                                    Axis3.computeAxis3(r, g, b)//重算第三轴
                                    val pc = when (Axis3.type) {//计算受第三轴影响下实际位置对应的原颜色值
                                        R -> Color(0, g, b)
                                        G -> Color(r, 0, b)
                                        B -> Color(r, g, 0)
                                        null -> curRGB
                                    }
                                    curPos = with(color2offset(pc)) {
                                        IntOffset(x.toInt(), y.toInt())
                                    }
                                }) {
                            Text(
                                text = "${
                                    when (curTp) {
                                        使用量 -> it.useCount
                                        使用时间 -> longTime2String(
                                            it.time,
                                            if (System.currentTimeMillis() - it.time > 24 * 60 * 60 * 1000) "MM/dd" else "HH:mm"
                                        )

                                        收藏 -> it.id.toHexString()
                                    }
                                }", fontSize = 10.sp, color = it.reColor,
                                modifier = Modifier.align(Alignment.Center)
                            )
                        }
                    }
                    if (lst.size != 4) Spacer(Modifier.weight(4f - lst.size))
                }
            }
        }
    }
}